package org.servlet;

import org.domain.Account;
import org.domain.Cart;
import org.domain.Item;
import org.service.CartService;
import org.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import org.apache.log4j.Logger;

public class AddToCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/JSP/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/JSP/common/Error.jsp";

    private Cart cart;
    private String workingItemId = "0";
    private CatalogService catalogService;
    private CartService cartService;
    private static Logger logger = Logger.getLogger(Class.class);
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if(session.getAttribute("account")==null)
        {
            session.setAttribute("message","Please Sign In At First!");
            request.getRequestDispatcher(ERROR).forward(request,response);
            return;
        }
        cartService = new CartService();
        workingItemId = request.getParameter("workingItemId");
            cart = (Cart)session.getAttribute("cart");

            if(cart==null)
            {
                cart = new Cart();
            }

            if(cart.containsItemId(workingItemId))
            {
                cart.incrementQuantityByItemId(workingItemId);
                if(session.getAttribute("account")!=null)
                {
                    Account account = (Account)session.getAttribute("account");
                    cartService.incrementQuantityByItemId(account.getUsername(),workingItemId);
                }
            }
            else
            {
                catalogService = new CatalogService();
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item,isInStock);
                if(session.getAttribute("account")!=null)
                {
                    Account account = (Account) session.getAttribute("account");
                    cartService.addItem(account.getUsername(),workingItemId);
                    logger.info(String.format("User (%s) Add a New Item (%s)",account.getUsername(),workingItemId));
                }
            }
            session.setAttribute("cart",cart);
            request.getRequestDispatcher(VIEW_CART).forward(request,response);
        }
}
